import { Component } from 'vue-property-decorator'
import Styles from '@/views/organizationManagement/apply.less'
import UpdateStyles from './update.less'
import SelectTree from '@/components/SelectTree'
import SelectTreeEmpty from '@/modules/selectTreeEmpty'
import CreateUpdateMixin from './createUpdateMixin'
import Upload from '@/components/Upload'
import { callSuperMethod } from '@/lib/utils'
import organize from '@/lib/request/organize'

const formRule = {
  area: [
    {
      required: true,
      message: '机构所属区域不能为空',
      trigger: 'blur',
    },
  ],
  parentOrgCode: [
    {
      required: true,
      message: '请选择更新机构',
    },
  ],
  orgName: [
    {
      required: true,
      message: '机构单位名称不能为空',
      trigger: 'blur',
    },
  ],
  licenseNumber: [
    {
      required: true,
      message: '统一社会信用代码不能为空',
      trigger: 'blur',
    },
    {
      len: 18,
      message: '长度没有达到 18 位',
      trigger: 'blur',
    },
  ],
}

interface OrgDetail {
  uuid: string
  fullName: string
  organizeType: number
  licenseType: number
  licenseNumber: string
  organizeCode?: string
  parentCode?: string
  parentOrgName?: string
}

@Component({})
export default class OrganizationManagement extends CreateUpdateMixin {
  formData: any = {
    orgName: '',
    orgType: 1,
    licenseType: 1,
    licenseNumber: '',
    officer: '',
    mobile: '',
    applyType: 1, // 0-新增，1-更新
    originOrgCode: '',
  }

  upperName?: string = ''

  cachedForm: any = {}

  protected render() {
    return (
      <div
        class={[
          Styles.organizationApplyView,
          UpdateStyles.organizationUpdateView,
        ]}
      >
        {!this.isDone && (
          <el-form
            label-width="150px"
            size="mini"
            ref="form"
            {...{
              props: { model: this.formData, rules: formRule },
            }}
          >
            <h1>
              <i>*</i>机构选择
            </h1>
            <div class="area-info">
              <el-form-item label="原机构" prop="area" class="line-height22">
                <el-cascader
                  ref="areaSelect"
                  v-model={this.formData.area}
                  options={this.areaData}
                  show-all-levels={false}
                  onChange={this.areaChange}
                  placeholder="请选择区域"
                  {...{
                    props: {
                      props: {
                        value: 'uuid',
                        label: 'fullName',
                        children: 'subList',
                      },
                    },
                  }}
                />
              </el-form-item>
              <el-form-item class="select-org" prop="parentOrgCode">
                <SelectTree
                  ref="selectTree"
                  class="query-select"
                  loading={this.loadTree}
                  parentId={this.formData.area.slice(-1)[0]}
                  value={this.formData.parentOrgName}
                  onInit={this.getAllTree}
                  defaultExpended={this.defaultExpended}
                  defaultProps={{ minSearchSize: 2 }}
                  onHandleNodeClick={this.selectOrg}
                  onError={this.selectTreeError}
                >
                  <template slot="empty">
                    <SelectTreeEmpty>
                      <p>
                        （1）请确认已输入机构名称是否正确无误，可模糊搜索；
                        <br />
                        （2）如确认名称无误但系统内缺失，请在本页面提交证明材料等待审核通过后，重新发起印章申请。
                      </p>
                    </SelectTreeEmpty>
                  </template>
                </SelectTree>
                {/* <el-tooltip class="item" effect="dark" content="请选择本机构的直接或间接归属机构" placement="bottom-start">
                <i class="el-icon-question"/>
              </el-tooltip> */}
              </el-form-item>
            </div>
            <h1>
              <i>*</i>机构信息更新
            </h1>
            <el-form-item label="上级机构">
              <el-input value={this.upperName} disabled />
            </el-form-item>
            <el-form-item label="机构单位名称" prop="orgName">
              <el-input v-model={this.formData.orgName} />
            </el-form-item>
            <el-form-item label="统一社会信用代码" prop="licenseNumber">
              <el-input maxlength={18} v-model={this.formData.licenseNumber} />
            </el-form-item>
            <el-form-item label="联系人">
              <el-input v-model={this.formData.officer} />
            </el-form-item>
            <el-form-item label="手机号码" style="padding-bottom: 12px">
              <el-input v-model={this.formData.mobile} />
            </el-form-item>
            <div class="upload-box">
              <el-form-item label="上传机构单位统一社会信用代码证">
                {!this.formData.licenseFileKey && (
                  <Upload
                    content="点击上传"
                    file={this.file}
                    action={this.uploadUrl}
                    success={this.uploadSuccess}
                    error={this.uploadError}
                    beforeUpload={this.beforeUpload}
                  />
                )}
                {this.formData.licenseFileKey && (
                  <div class="preview-img">
                    <div class="over-layer">
                      <i class="el-icon-search" />
                    </div>
                    <i class="el-icon-delete" onclick={this.deleteImageEvt} />
                    <el-image
                      style="width: 100%; height: 100%"
                      src={this.formData.licenseFileUrl}
                      preview-src-list={[this.formData.licenseFileUrl]}
                    />
                  </div>
                )}

                <div class="help-info">
                  上传须知:
                  <br /> 1、图片按照A4纸大小扫描，像素300dpi <br />
                  2、格式须为PNG/JPG/JPEG <br />
                  3、为提高审核通过率请确保单位名称和统一社会信用代码清晰可见，且和申请表保持一致
                </div>
              </el-form-item>
            </div>
            <el-form-item class="footer">
              <el-button onClick={() => this.$router.go(-1)}>关闭</el-button>
              <el-button type="primary" onClick={this.submit}>
                提交
              </el-button>
            </el-form-item>
          </el-form>
        )}

        {this.isDone && (
          <div class="success-view">
            <i class="el-icon-circle-check" />
            <h1>提交成功！请耐心等待审核</h1>
            <p>{this.timer} 秒后返回组织机构更新申请</p>

            <el-button class="link-btn" onClick={() => this.gotoListPage(true)}>
              前往查看
            </el-button>
            <p>在组织机构更新中可以查看审核结果</p>
          </div>
        )}
      </div>
    )
  }

  async mounted() {
    await this.remoteAreaData()
    this.formData.officer = this.name
    this.formData.mobile = this.accountMobile
    if (this.$route.query.orgInfo) {
      const [areaId, orgUUid] = this.$route.query.orgInfo.toString().split('-')
      this.setDefaultArea(this.areaData, areaId)
      this.setOrgDetail(orgUUid)
    }
  }

  setDefaultArea(areaData: any[], areaId: string) {
    let areaIndex1 = -1
    let areaIndex2 = -1
    areaIndex1 = this.areaData.findIndex(i => i.uuid === areaId)
    if (areaIndex1 !== -1) {
      this.formData.area = [areaId]
    } else {
      areaIndex1 = this.areaData.findIndex(area => {
        if (!area.subList) {
          return false
        }
        areaIndex2 =
          area.subList && area.subList.findIndex((i: any) => i.uuid === areaId)

        return areaIndex2 > -1
      })
      this.formData.area = [areaData[areaIndex1].uuid, areaId]
    }
  }

  async selectOrg(val: any) {
    callSuperMethod(this, 'selectOrg', [val])
    if (val.uuid) {
      this.clearDefaultFormData()
      this.setOrgDetail(val.uuid)
    }
  }

  async setOrgDetail(orgUUid: string) {
    const res = await organize.getOrganizeDetail(orgUUid)
    this.setDefaultFormData(res.data)
    this.cachedForm = {
      orgName: this.formData.orgName,
      licenseNumber: this.formData.licenseNumber,
    }
  }

  clearDefaultFormData() {
    this.formData.orgName = ''
    this.formData.licenseNumber = ''
  }

  setDefaultFormData(detail: OrgDetail) {
    this.formData = Object.assign({}, this.formData, {
      orgName: detail.fullName,
      licenseNumber: detail.licenseNumber,
      parentOrgName: detail.fullName,
      parentOrgCode: detail.parentCode,
      originOrgCode: detail.organizeCode,
    })
    this.upperName = detail.parentOrgName
  }

  submit() {
    if (
      this.cachedForm.orgName === this.formData.orgName &&
      this.cachedForm.licenseNumber === this.formData.licenseNumber
    ) {
      this.$confirm(
        '请修改 “机构单位名称” 或  “统一社会信用代码” 内容后进行提交',
        '提示',
        {
          confirmButtonText: '知道了',
          type: 'warning',
          closeOnPressEscape: false,
          closeOnClickModal: false,
          showClose: true,
          showCancelButton: false,
        }
      )

      return
    }
    this.submitEvt()
  }
}
